package zwz.importTask.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zwz.importTask.VO.ResultInfo;
import zwz.importTask.enums.ImportAndExportTaskEnum;
import zwz.importTask.strategy.AbstractExcelExportStrategy;
import zwz.importTask.strategy.AbstractExcelImportStrategy;
import zwz.importTask.utils.ImportThreadLocalUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/taskImportCenter")
public class ImportAndExportController {

    @Autowired
    private Map<String, AbstractExcelImportStrategy> importStrategyMap;

    @Autowired
    private Map<String, AbstractExcelExportStrategy> exportStrategyMap;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;


    @PostMapping("/import")
    public ResultInfo importFile(@RequestParam("file") MultipartFile file, @RequestParam("fileType") Integer fileType) throws Exception {
        String filename = file.getOriginalFilename();

        byte[] fileData = file.getBytes();

        // 获取策略
        AbstractExcelImportStrategy<?> strategy = importStrategyMap.get(ImportAndExportTaskEnum.getStrategyByType(fileType));
        if (null == strategy) return ResultInfo.error("未找到导入策略");

        // 异步执行任务
        taskExecutor.execute(() -> {
            try {
                strategy.doImport(fileData, fileType, filename);
            } catch (Exception e) {
                log.error("导入任务执行失败", e);
            } finally {
                ImportThreadLocalUtils.remove();
            }
        });

        return ResultInfo.success("已导人，请前往文件中心查看");
    }


    @GetMapping("/export")
    public ResultInfo asyncExportFileFlow(@RequestParam("fileType") Integer fileType, HttpServletResponse response, @RequestParam("params") String params) {

        AbstractExcelExportStrategy<?> strategy = exportStrategyMap.get(ImportAndExportTaskEnum.getStrategyByType(fileType));
        if (null == strategy) return ResultInfo.error("未找到导出策略");
        taskExecutor.execute(() -> {
            try {
                strategy.doExport(fileType, response,params);
            } catch (IOException e) {
                log.info("导出失败：{}", e);
            }finally {
                ImportThreadLocalUtils.remove();
            }
        });

        return ResultInfo.success("已导出，请前往文件中心查看");
    }


}
